package com.dimpt.cloud.common.utils;

import com.dimpt.cloud.common.config.ResponseInfo;
import com.dimpt.cloud.common.exception.FailedException;

import java.io.Serializable;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.List;

/**
 * @ClassName PageUtils
 * @Description 分页定义
 * @Author Liujf
 * @Date 2019/5/23 8:49
 * @Version 1.0
 **/
public class PageUtils<T> implements Serializable {

    private static final long serialVersionUID = 5760097915453738435L;
    public static final int DEFAULT_PAGE_SIZE = 10;

    private int totalCount; //总条数

    private int totalPage; //总页数

    private int pageSize;   //每页条数

    private int currentPage; //当前页数

    private List<T> rows;    //数据

    public PageUtils(){
        this.currentPage = 1;
        this.pageSize = DEFAULT_PAGE_SIZE;
    }

    public PageUtils(int currentPage,int pageSize,List<T> rows){

        this.currentPage = currentPage <= 0 ? 1 : currentPage;
        this.pageSize = pageSize <= 0 ? DEFAULT_PAGE_SIZE : pageSize;
        this.totalCount = rows.size();
        this.totalPage = this.totalCount % pageSize == 0 ? this.totalCount / pageSize : (this.totalCount / pageSize + 1);
        if(this.totalCount > 0){
            if(this.currentPage > this.totalPage){
                this.rows = Arrays.asList();
                //throw new FailedException(ResponseInfo.PAGE_ERROR.getErrorCode(),ResponseInfo.PAGE_ERROR.getErrorMsg());
            }else{
                int startIndex = this.pageSize * ( this.currentPage -1 );
                int endIndex = 0;
                if(this.pageSize * this.currentPage > this.totalCount){
                    endIndex = this.totalCount;
                }else{
                    endIndex = this.pageSize * this.currentPage ;
                }

                this.rows = rows.subList(startIndex,endIndex);
            }
        }else{
            this.rows = rows;
        }
    }
    public int getPageSize() {
        return pageSize;
    }

    public int getCurrentPage() {
        return currentPage;
    }

    public int getTotalPage() {
        return totalPage;
    }

    public int getTotalCount() {
        return totalCount;
    }

    public List<T> getRows() {
        return rows;
    }
}
